package zbase;

import javax.swing.JOptionPane;

public class InstallDBDialog extends javax.swing.JDialog {

    private String result = "False";

    public InstallDBDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        jLabel3.setText("");
        DB db = new DB();
        if (db.executeNonQuery("SELECT k FROM zmain WHERE k = 0") != 0) {
            jLabel3.setText(jLabel3.getText() + " zmain");
        }
        if (db.executeNonQuery("SELECT k FROM objects WHERE k = 0") != 0) {
            jLabel3.setText(jLabel3.getText() + " objects");
        }
        if (db.executeNonQuery("SELECT k FROM services WHERE k = 0") != 0) {
            jLabel3.setText(jLabel3.getText() + " services");
        }
        if (db.executeNonQuery("SELECT k FROM users WHERE k = 0") != 0) {
            jLabel3.setText(jLabel3.getText() + " users");
        }
    }

    public String getResult() {
        return result;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Установка таблиц базы данных");
        setResizable(false);

        jButton1.setText("Выход");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Установить");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Необходимо установить следующие таблицы:");

        jLabel3.setText("tables");

        jLabel4.setText("Существующие данные затронуты не будут.");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        result = "ExitPressed";
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        WaitingWindow ww = new WaitingWindow();

        DB db = new DB();

        if (db.executeNonQuery("SELECT k FROM zmain WHERE k = 0") != 0) {
            db.executeNonQuery("CREATE TABLE zmain (" +
                    "k int(10) unsigned NOT NULL auto_increment, " +
                    "zdatetime datetime NOT NULL, " +
                    "zobject int(10) unsigned NOT NULL, " +
                    "ztext text NOT NULL, " +
                    "zservice int(10) unsigned NOT NULL, " +
                    "zprim text NOT NULL, " +
                    "zalert tinyint(1) NOT NULL, " +
                    "zdone tinyint(1) NOT NULL, " +
                    "zdonedt datetime default NULL, " +
                    "hide tinyint(1) NOT NULL, " +
                    "PRIMARY KEY (k)) ENGINE=InnoDB DEFAULT CHARSET=utf8");
        }
        if (db.executeNonQuery("SELECT k FROM objects WHERE k = 0") != 0) {
            db.executeNonQuery("CREATE TABLE objects (" +
                    "k int(10) unsigned NOT NULL auto_increment, " +
                    "objname varchar(1024) NOT NULL, " +
                    "hide tinyint(1) NOT NULL, " +
                    "PRIMARY KEY (k)) ENGINE=InnoDB DEFAULT CHARSET=utf8");
        }
        if (db.executeNonQuery("SELECT k FROM services WHERE k = 0") != 0) {
            db.executeNonQuery("CREATE TABLE services (" +
                    "k int(10) unsigned NOT NULL auto_increment, " +
                    "servicename varchar(1024) NOT NULL, " +
                    "hide tinyint(1) NOT NULL, " +
                    "PRIMARY KEY (k)) ENGINE=InnoDB DEFAULT CHARSET=utf8");
        }
        Boolean userscreated = false;
        if (db.executeNonQuery("SELECT k FROM users WHERE k = 0") != 0) {
            db.executeNonQuery("CREATE TABLE users (" +
                    "k int(10) unsigned NOT NULL auto_increment, " +
                    "username varchar(1024) NOT NULL, " +
                    "userpass varchar(1024) NOT NULL, " +
                    "admin tinyint(1) NOT NULL, " +
                    "canzmain tinyint(1) NOT NULL, " +
                    "canobjects tinyint(1) NOT NULL, " +
                    "canservices tinyint(1) NOT NULL, " +
                    "hide tinyint(1) NOT NULL, " +
                    "PRIMARY KEY (k)) ENGINE=InnoDB DEFAULT CHARSET=utf8");
            db.executeNonQuery("INSERT INTO users (username, userpass, admin, canzmain, canobjects, canservices, hide) " +
                    "VALUES (" +
                    "\"" + String.valueOf("admin") + "\", " +
                    "\"" + String.valueOf("admin".hashCode()) + "\", " +
                    "1, 1, 1, 1, 0)");
            userscreated = true;
        }

        ww.close();

        if (userscreated) {
            JOptionPane.showMessageDialog(null, "Создан пользователь по умолчанию. Имя пользователя - admin, пароль - admin.", "Сообщение", JOptionPane.INFORMATION_MESSAGE);
        }

        JOptionPane.showMessageDialog(null, "Новые таблицы созданы успешно.", "Сообщение", JOptionPane.INFORMATION_MESSAGE);
        result = "Ok";
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    // End of variables declaration//GEN-END:variables
}
